package com.taotao.order.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShippingMapper;
import com.taotao.order.dao.JedisClient;
import com.taotao.order.service.OrderService;
import com.taotao.pojo.TbOrder;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderShipping;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private TbOrderMapper orderMapper;
	@Autowired
	private TbOrderItemMapper orderItemMapper;
	@Autowired
	private TbOrderShippingMapper orderShippingMapper;
	@Autowired
	// 订单id和订单明细id采用redis的incr方法获取
	private JedisClient jedisClient;
	@Value("${ORDER_GEN_KEY}")
	private String ORDER_GEN_KEY;
	@Value("${ORDER_INIT_ID}")
	private long ORDER_INIT_ID;
	@Value("${ORDER_DETAIL_GEN_KEY}")
	private String ORDER_DETAIL_GEN_KEY;

	@Override
	public TaotaoResult createOrder(TbOrder order, List<TbOrderItem> orderItemList, TbOrderShipping orderShipping) {
		long orderId = jedisClient.incr(ORDER_GEN_KEY);
		// 如果orderId<ORDER_INIT_ID,就初始化一下orderId
		if (orderId < ORDER_INIT_ID) {
			jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID + "");
			orderId = jedisClient.incr(ORDER_GEN_KEY);
		}
		// 补全pojo属性
		order.setOrderId(orderId + "");
		// 状态:1 未付款,2 已付款,3 未发货,4 已发货,5 交易成功,6 交易结束
		order.setStatus(1);
		Date date = new Date();
		order.setCreateTime(date);
		order.setUpdateTime(date);
		// 0:未评价,1:已评价
		order.setBuyerRate(0);
		orderMapper.insert(order);
		for (TbOrderItem orderItem : orderItemList) {
			long orderItemId = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
			orderItem.setId(orderItemId + "");
			orderItem.setOrderId(orderId + "");
			orderItemMapper.insert(orderItem);
		}
		orderShipping.setOrderId(orderId + "");
		orderShipping.setCreated(date);
		orderShipping.setUpdated(date);
		orderShippingMapper.insert(orderShipping);

		return TaotaoResult.ok(orderId);
	}

}
